use axum::{extract::Path, http::StatusCode, Json};
use serde::{Deserialize, Serialize};

pub mod interface;
pub mod model;

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateTaskBody {
    name: String,
    size: i64,
}
// 创建任务
pub async fn create_task(
    Json(payload): Json<CreateTaskBody>,
) -> (StatusCode, Json<serde_json::Value>) {
    let task = interface::Task::default(&payload.name, &payload.size);
    match model::add_task(&task).await {
        Ok(_) => (
            StatusCode::CREATED,
            Json(serde_json::json!({
                "success":true,
                "message":"操作成功",
                "data":task
            })),
        ),
        Err(err) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({
                "success":false,
                "message":format!("{:?}",err),
            })),
        ),
    }
}

pub async fn task(Path(task_id): Path<String>) -> (StatusCode, Json<serde_json::Value>) {
    match model::select_task(&task_id).await {
        Ok(task) => match task {
            Some(value) => (
                StatusCode::OK,
                Json(serde_json::json!({
                    "success":true,
                    "message":"操作成功",
                    "data":value
                })),
            ),
            None => (
                StatusCode::OK,
                Json(serde_json::json!({
                    "success":true,
                    "message":"查无记录",
                })),
            ),
        },
        Err(err) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({
                "success":false,
                "message":format!("{:?}",err),
            })),
        ),
    }
}
